package com.reader.api.controller.order;

import com.reader.api.constants.GoodsTypeEnum;
import com.reader.api.constants.PayPlatformTypeEnum;
import com.reader.api.controller.BaseController;
import com.reader.api.pay.PayService;
import com.reader.api.pay.request.OrderRequest;
import com.reader.api.pay.request.PayCallbackRequest;
import com.reader.api.pay.response.PayCallbackResponse;
import com.reader.core.entity.ResultMessageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author liujianqing
 * @date 2018/10/25
 */
@RestController
@RequestMapping("/api/order/")
public class OrderController extends BaseController<Object> {
    @Autowired
    private PayService payService;

    @RequestMapping(value = "/commit", method = RequestMethod.POST)
    @ResponseBody
    public ResultMessageInfo commit(@RequestBody OrderRequest orderRequest,
                                    HttpServletRequest request) {


        if(orderRequest == null){
            return ResultMessageInfo.ofMessage("参数错误");
        }

        if(StringUtils.isBlank(orderRequest.getGoodsId())){
            return ResultMessageInfo.ofMessage("请选择正确的商品");
        }

        PayPlatformTypeEnum payTypeEnum = PayPlatformTypeEnum.getEnumByCode(orderRequest.getPayMode());
        if (payTypeEnum==null){
            return ResultMessageInfo.ofMessage("请选择支付平台");
        }
        GoodsTypeEnum goodsTypeEnum = GoodsTypeEnum.getEnumByCode(orderRequest.getGoodsType());
        if (goodsTypeEnum==null){
            return ResultMessageInfo.ofMessage("请选择正确的商品");
        }
        PayCallbackRequest payCallbackRequest = new PayCallbackRequest();
        PayCallbackResponse payCallbackResponse = payService.payCallback(payCallbackRequest);

        return ResultMessageInfo.ofSuccess(payCallbackResponse);
    }

    @RequestMapping(value = "/pay/{payPlatformType}/callback", method = RequestMethod.POST)
    @ResponseBody
    public ResultMessageInfo callback(@RequestParam String orderNum,
                                      @PathVariable String payPlatformType) {


        if(StringUtils.isBlank(orderNum)){
            return ResultMessageInfo.ofMessage("支付订单号不能为空");
        }

        PayPlatformTypeEnum payTypeEnum = PayPlatformTypeEnum.getEnumByCode(payPlatformType);
        if (payTypeEnum==null){
            return ResultMessageInfo.ofMessage("支付平台错误");
        }
        PayCallbackRequest payCallbackRequest = new PayCallbackRequest();
        PayCallbackResponse payCallbackResponse = payService.payCallback(payCallbackRequest);

        return ResultMessageInfo.ofSuccess(payCallbackResponse);
    }

}
